from typing import Optional

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if head is None:
            return None
        if k == 0:
            return head
        stack, cur = [], head
        while cur:
            stack.append(cur)
            cur = cur.next
        
        deep = len(stack)
        k = k % deep
        if k == 0:
            return head
        stack[-1].next = head
        stack[-k - 1].next = None
        return stack[-k]
            
